using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;

namespace Microsoft.EntityFrameworkCore.Metadata.Conventions;

public class DmValueGenerationConvention : RelationalValueGenerationConvention
{
	public DmValueGenerationConvention([NotNull] ProviderConventionSetBuilderDependencies dependencies, [NotNull] RelationalConventionSetBuilderDependencies relationalDependencies)
		: base(dependencies, relationalDependencies)
	{
	}

	public override void ProcessPropertyAnnotationChanged(IConventionPropertyBuilder propertyBuilder, string name, IConventionAnnotation annotation, IConventionAnnotation oldAnnotation, IConventionContext<IConventionAnnotation> context)
	{
		if (name == "Dm:ValueGenerationStrategy")
		{
			propertyBuilder.ValueGenerated(this.GetValueGenerated(propertyBuilder.Metadata), false);
		}
		else
		{
			this.ProcessPropertyAnnotationChanged(propertyBuilder, name, annotation, oldAnnotation, context);
		}
	}

	protected override ValueGenerated? GetValueGenerated(IConventionProperty property)
	{
		return this.GetValueGenerated(property);
	}

	public static ValueGenerated? GetValueGenerated([NotNull] IProperty property)
	{
		ValueGenerated? valueGenerated = ValueGenerationConvention.GetValueGenerated(property);
		if (!valueGenerated.HasValue)
		{
			if (property.GetValueGenerationStrategy() == DmValueGenerationStrategy.None)
			{
				return null;
			}
			return (ValueGenerated)1;
		}
		return valueGenerated;
	}
}
